package com.jl.registermvc;

import com.jl.annotation.JMvc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.MergedAnnotation;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;

/**
 * 这个是第二步
 * 通过注解启动了第一个步骤后，执行添加到容器中
 */
@Slf4j
public class ContractAutoHandlerRegisterConfiguration implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        //获取启动类包路径
        String basePackage = ClassUtils.getPackageName(metadata.getClassName());
        //获取是否启动类注解参数
        MergedAnnotations annotations = metadata.getAnnotations();
        MergedAnnotation<JMvc> jlMvcMergedAnnotation = annotations.get(JMvc.class);
        boolean isInterfaceNameSmall = jlMvcMergedAnnotation.getBoolean("isInterfaceNameSmall");
        //生成BeanDefinition并注册到容器中
        BeanDefinitionBuilder mappingBuilder = BeanDefinitionBuilder.genericBeanDefinition(ContractAutoHandlerRegisterHandlerMapping.class);
        mappingBuilder.addConstructorArgValue(basePackage);
        mappingBuilder.addConstructorArgValue(isInterfaceNameSmall);
        try {
            Class<?> forName = Class.forName("com.jl.config.ConciseMvcRegisterConfig");
            if (forName != null) {
                mappingBuilder.addDependsOn("conciseMvcRegisterConfig");
            }
        } catch (ClassNotFoundException e) {
            log.error(e.getMessage(), e);
        }
        registry.registerBeanDefinition("contractAutoHandlerRegisterHandlerMapping", mappingBuilder.getBeanDefinition());
        BeanDefinitionBuilder processBuilder = BeanDefinitionBuilder.genericBeanDefinition(ContractReturnValueWebMvcConfigurer.class);
        registry.registerBeanDefinition("contractReturnValueWebMvcConfigurer", processBuilder.getBeanDefinition());
    }

}
